<script setup lang="ts">
import {Plus} from "@element-plus/icons-vue";
import type {CurrentSaleAttr, SaleAttr, SaleAttrValue, SpuData, SPUImage} from "@/api/product/spu/type.ts";
// 编辑时要发的请求
import {reqAllSaleAttr, reqImages, reqSaleAttr, reqTradeMark, reqSaveOrUpdateSPU} from '@/api/product/spu/index.ts';
import {computed, nextTick, ref} from "vue";
import {TradeMark} from "@/api/product/trademark/type.ts";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css';

let emits = defineEmits(['changeScene']);

let AllTradeMark = ref<TradeMark[]>([])
let imgList = ref<SPUImage[]>([]);
let saleAttrs = ref<SaleAttr[]>([])
let allSaleAttrs = ref<CurrentSaleAttr[]>([]);

let SpuParam = ref<SpuData>({
  category3Id: "",
  description: "",
  spuName: "",
  saleAttrList: null,
  spuImageList: null,
  tmId: "",
});

const cancel = () => {
  // 通知父组件index，返回场景0
  emits("changeScene", 0);
}


const init = async (spu: SpuData) => {
  SpuParam.value = spu;
  let tradeMark = await reqTradeMark();
  let imgs = await reqImages((spu.id as number));
  let allSaleAttr = await reqAllSaleAttr();
  let saleAttr = await reqSaleAttr((spu.id as number));

  AllTradeMark.value = tradeMark.data.data;
  imgList.value = imgs.data.data.map((item: SPUImage) => {
    return {"name": item.imgName, "url": item.imgUrl}
  });
  saleAttrs.value = saleAttr.data.data;
  allSaleAttrs.value = allSaleAttr.data.data;
}

// 照片墙
let dialogVisible = ref<boolean>(false);
let dialogImageUrl = ref<string>();
const handlePictureCardPreview = (file: any) => {
  // 预览图片
  dialogVisible.value = true;
  // 预览图片的Url
  dialogImageUrl.value = file.url;
}

// 销售属性值添加
let InputRef = ref();
let showInput = (row: SaleAttr) => {
  row.flag = true;
  nextTick(() => {
    InputRef.value.focus();
  })
}

const handleInputConfirm = (row: SaleAttr) => {
  if (!row.saleAttrValue) {
    row.flag = false;
    row.saleAttrValue = '';
    ElMessage.warning("属性值不能为空");
    return;
  }

  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == row.saleAttrValue;
  });
  if (repeat) {
    row.flag = false;
    row.saleAttrValue = '';
    ElMessage.error("属性值不能重复");
    return;
  }

  let attrValue: SaleAttrValue = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.saleAttrValue,
  }
  row.spuSaleAttrValueList.push(attrValue);
  row.flag = false;
}

// 计算未使用的销售属性
let unUsedSaleAttr = computed(() => {
  return allSaleAttrs.value.filter((item) => {
    return saleAttrs.value.every((item1) => {
      return item1.saleAttrName != item.name;
    })
  });
})
// 收集选择的未使用的销售属性
let unUsedAttr = ref<string>('');
// 添加销售属性
const addSaleAttr = () => {
  // 数组解构
  let [temp, saleAttrName] = unUsedAttr.value.split(":");
  let baseSaleAttrId: number = parseInt(temp);
  let newAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  saleAttrs.value.push(newAttr);

  unUsedAttr.value = '';
}


const save = async () => {
  SpuParam.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url
    }
  });
  SpuParam.value.saleAttrList = saleAttrs.value;

  console.log(SpuParam.value);

  let result = await reqSaveOrUpdateSPU(SpuParam.value);
  if (result.data.code === 200) {
    ElMessage({
      type:"success",
      message:SpuParam.value.id?"编辑成功":"添加成功"
    });
    emits("changeScene",0);
  } else {
    ElMessage({
      type:"error",
      message:SpuParam.value.id?"编辑失败":"添加失败"
    })
  }

}

// 添加SPU时初始化
const initAdd = async (c3ID: number)=>{
  // 清空数据
  Object.assign(SpuParam,{
    category3Id: "",
    description: "",
    spuName: "",
    saleAttrList: null,
    spuImageList: null,
    tmId: "",
  })
  imgList.value = [];
  allSaleAttrs.value = [];
  unUsedAttr.value = '';

  SpuParam.value.category3Id = c3ID;

  let tradeMark = await reqTradeMark();
  let allSaleAttr = await reqAllSaleAttr();
  AllTradeMark.value = tradeMark.data.data;
  allSaleAttrs.value = allSaleAttr.data.data;
}
// 暴露接口
defineExpose({init,initAdd});
</script>

<template>
  <el-form label-position="right" style="width: 60%" label-width="100px">
    <el-form-item label="SPU名称">
      <el-input v-model="SpuParam.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParam.tmId">
        <el-option v-for="item in AllTradeMark" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="描述">
      <el-input type="textarea" v-model="SpuParam.description"></el-input>
    </el-form-item>

    <el-form-item label="图片">
      <el-upload
          v-model:file-list="imgList"
          action="https://sph-api.atguigu.cn/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview">
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select v-model="unUsedAttr" :placeholder="unUsedSaleAttr.length?`还有${unUsedSaleAttr.length}个`:'无'">
        <el-option :value="`${item.id}:${item.name}`" v-for="item in unUsedSaleAttr" :key="item.id"
                   :label="item.name"></el-option>
      </el-select>
      <el-button @click="addSaleAttr" :disabled="!unUsedAttr" icon="plus" type="primary" style="margin-left: 20px">
        添加销售属性
      </el-button>

      <!-- 销售属性和值  -->
      <el-table
          border
          style="margin: 10px 0"
          :data="saleAttrs">
        <el-table-column label="序号" align="center" width="80px"></el-table-column>
        <el-table-column label="销售属性" align="center" width="100px" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值" align="center">
          <template #default="{row,$index}">
            <el-tag
                v-for="item in row.spuSaleAttrValueList"
                closable
                type="warning"
                style="margin: 5px"
                @close="row.spuSaleAttrValueList.splice($index,1)"
                :key="item.id">
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
                v-if="row.flag"
                ref="InputRef"
                v-model="row.saleAttrValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
                style="width: 100px"
            />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              +
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80px">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="saleAttrs.splice(scope.$index,1)">

            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">

</style>